package com.example.supermonkeysm.security.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.supermonkeysm.dao.UserMapper;
import com.example.supermonkeysm.entity.User;
import com.example.supermonkeysm.security.dao.MenuMapper;
import com.example.supermonkeysm.security.dao.RoleMapper;
import com.example.supermonkeysm.security.entity.*;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.annotation.Resource;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录校验
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("登录中!");
        if(username == null || StringUtils.isBlank(username))throw new UsernameNotFoundException("请输入用户名!");

        MPJLambdaWrapper<User> userMPJLambdaWrapper = new MPJLambdaWrapper<>();
        userMPJLambdaWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(userMPJLambdaWrapper);
        if (user == null)throw new UsernameNotFoundException("用户名不存在!");

        MPJLambdaWrapper<Role> roleMapperMPJLambdaWrapper = new MPJLambdaWrapper<>();
        roleMapperMPJLambdaWrapper.select(Role::getEnName)
                .innerJoin(UsersRoles.class, "ur", on -> on.eq(UsersRoles::getRoleId, Role::getId))
                .innerJoin(User.class, "u", on -> on.eq(UsersRoles::getUserId, User::getId))
                .eq(User::getUsername, user.getUsername());
        List<Object> roles = roleMapper.selectObjs(roleMapperMPJLambdaWrapper);//获得用户角色

        MPJLambdaWrapper<Menu> menuMPJLambdaWrapper = new MPJLambdaWrapper<>();
        menuMPJLambdaWrapper.selectAll(Menu.class)
                .innerJoin(RolesMenus.class,"rm", on->on.eq(RolesMenus::getMenuId,Menu::getId))
                .innerJoin(Role.class,"r", on->on.eq(Role::getId,RolesMenus::getRoleId))
                .in(Role::getEnName,roles);
        List<Menu> menus = menuMapper.selectList(menuMPJLambdaWrapper);//获得角色菜单

        return new DetailsUser(user.getId(),user.getUsername(),user.getPassword(),roles,menus);

    }
}
